<!DOCTYPE html>
<html>
<head lang="en">
	<base href="/">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="UTF-8">
	<title>我的</title>
	<link href="css/base.css" type="text/css" rel="stylesheet">
	<link href="css/kind.css" type="text/css" rel="stylesheet">
	<link href="css/my.css" type="text/css" rel="stylesheet">
	<!-- 引入 Layui 的 CSS 文件 -->
	<link rel="stylesheet" href="layui/css/layui.css">
	<!--[if lt IE 9]>
	<script src="js/html5shiv.js"></script>
	<script src="js/respond.js"></script>
	<![endif]-->
</head>
<body>
<div class="my">
	<header>
		<a class="fl" href="#"><i class="iconfont">&#xe624;</i></a>
		<h2>我的</h2>
		<a href="#"><i class="iconfont">&#xe62b;</i></a>
	</header>
	<div class="myMsg">
		<div class="pic">
			<p></p>
			<!-- 用户头像 -->
			<a href="#"><img id="userAvatar" src="img/temp/pic.jpg" /></a>
			<p></p>
		</div>
		<!-- 用户名 -->
		<p class="userName" id="userName">尤物范儿</p>
	</div>
	<div class="navList">
		<nav>
			<a href="order.html"><i class="iconfont">&#xe606;</i>待付款</a>
			<a href="order.html"><i class="iconfont">&#xe63e;</i>待收货</a>
			<a href="order.html"><i class="iconfont">&#xe627;</i>已完成</a>
		</nav>
		<div class="subNav">
			<a href="shopping/totalorder"><i class="iconfont">&#xe603;</i><br/>全部订单</a>
			<a href="shopping/address"><i class="iconfont">&#xe614;</i><br/>我的地址</a>
			<a href="#"><i class="iconfont">&#xe689;</i><br/>我的收藏</a>
			<!-- 资料修改 -->
			<a id="editProfile"><i class="iconfont">&#xe6aa;</i><br/>资料修改</a>
			<!-- 添加地址 -->
			<a id="addAddress"><i class="iconfont">&#xe614;</i><br/>添加地址</a>
		</div>
	</div>
</div>
<div style="padding-top: 4rem;"></div>
<!--------------------------footer----------------------->
<footer>
	<a href="shopping/index" class="on"><i class="iconfont">&#xe60d;</i><br /><span>首页</span></a>
	<a href="shopping/cart"><i class="iconfont">&#xe6cc;</i><br /><span>购物车</span></a>
	<a href="#"><i class="iconfont">&#xe607;</i><br /><span>我</span></a>
</footer>

<!-- 资料修改模态框 -->
<div id="editModal" style="display:none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc; z-index: 1000;">
	<h2>修改资料</h2>
	<form id="editForm">
		<label for="username">用户名:</label>
		<input type="text" id="username" name="username" required><br><br>
		<label for="avatar">头像</label>
		<div class="layui-input-inline">
			<img src="img/temp/pic.jpg" id="avatarPreview" style="width: 100px;height: 100px;cursor:pointer">
			<input type="hidden" id="avatar" name="imgurl" required>
		</div>
		<br><br>
		<button type="submit">保存</button>
		<button type="button" id="closeModal">关闭</button>
	</form>
</div>

<!-- 添加地址模态框 -->
<div id="addAddressModal" style="display:none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc; z-index: 1000;">
	<h2>添加地址</h2>
	<form id="addAddressForm">
		<label for="contactName">联系人姓名:</label>
		<input type="text" id="contactName" name="contactName" required><br><br>
		<label for="tel">手机号码:</label>
		<input type="tel" id="tel" name="tel" required><br><br>
		<label for="province">省份:</label>
		<select id="province" name="province" required>
			<option value="">请选择省份</option>
		</select>
		<input type="hidden" id="provincecode" name="provincecode"><br><br>
		<label for="city">城市:</label>
		<select id="city" name="city" required>
			<option value="">请选择城市</option>
		</select>
		<input type="hidden" id="citycode" name="citycode"><br><br>
		<label for="area">区域:</label>
		<select id="area" name="area" required>
			<option value="">请选择区域</option>
		</select>
		<input type="hidden" id="areacode" name="areacode"><br><br>
		<label for="detailAddress">详细地址:</label>
		<input type="text" id="detailAddress" name="detailAddress" required><br><br>
		<button type="submit">保存</button>
		<button type="button" id="closeAddAddressModal">关闭</button>
	</form>
</div>

<!-- 引入 Layui 的 JS 文件 -->
<script src="layui/layui.all.js"></script>
<script src="js/public.js"></script>
<script src="js/rem.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-1.12.4.min.js"></script>

<script>
	$(document).ready(function() {
		// 高德地图 API 的密钥
		const amapKey = "d5e466c74f37e2b1f89163a68a161ea7";

		// 初始化 Layui 的 upload 模块
		layui.use('upload', function () {
			var upload = layui.upload;

			// 头像上传
			upload.render({
				elem: '#avatarPreview', // 绑定元素
				url: 'file/upload', // 上传接口
				done: function (res) {
					if (res.code === 0) { // 上传成功
						let imgUrl = res.data[0].src; // 获取图片地址
						$("#avatarPreview").attr("src", imgUrl); // 更新预览图
						$("#avatar").val(imgUrl); // 将图片地址赋值给隐藏域
					} else {
						layer.msg("上传失败", {icon: 2});
					}
				},
				error: function () {
					layer.msg("上传失败", {icon: 2});
				}
			});
		});

		// 发起 AJAX 请求获取当前用户信息
		$.ajax({
			url: "user/current", // 请求路径
			type: "GET",
			success: function(response) {
				if (response) {
					const userid = response.userid;
					window.userid = userid; // 将 userid 存储在全局变量中

					// 更新用户头像
					if (response.imgurl) {
						$("#userAvatar").attr("src", response.imgurl);
						$("#avatarPreview").attr("src", response.imgurl);
						$("#avatar").val(response.imgurl);
					}
					// 更新用户名
					if (response.username) {
						$("#userName").text(response.username);
						$("#username").val(response.username);
					}
				} else {
					console.log("未获取到用户信息");
				}
			},
			error: function(xhr, status, error) {
				console.error("获取用户信息失败:", error);
			}
		});

		// 点击“资料修改”按钮，显示模态框
		$("#editProfile").click(function() {
			$("#editModal").show();
		});

		// 点击“关闭”按钮，隐藏模态框
		$("#closeModal").click(function() {
			$("#editModal").hide();
		});

		// 提交表单，修改用户资料
		$("#editForm").submit(function(event) {
			event.preventDefault(); // 阻止表单默认提交行为

			// 获取表单数据
			var username = $("#username").val();
			var imgurl = $("#avatar").val();

			// 确保 userid 存在
			if (!window.userid) {
				alert("用户信息获取失败，请刷新页面重试！");
				return;
			}

			// 发起 AJAX 请求修改用户资料
			$.ajax({
				url: "user/edit", // 修改路径
				type: "POST",
				data: {
					userid: window.userid, // 使用全局变量 userid
					username: username,
					imgurl: imgurl
				},
				success: function(response) {
					if (response === 1) { // 假设返回 1 表示修改成功
						alert("资料修改成功！");
						// 更新页面上的用户名和头像
						$("#userName").text(username);
						$("#userAvatar").attr("src", imgurl);
						$("#editModal").hide(); // 关闭模态框
					} else {
						alert("资料修改失败，请重试！");
					}
				},
				error: function(xhr, status, error) {
					console.error("修改资料失败:", error);
					alert("修改资料失败，请重试！");
				}
			});
		});

		// 点击“添加地址”按钮，显示添加地址模态框
		$("#addAddress").click(function() {
			$("#addAddressModal").show();
			// 初始化省份下拉框
			loadProvinces();
		});

		// 点击“关闭”按钮，隐藏添加地址模态框
		$("#closeAddAddressModal").click(function() {
			$("#addAddressModal").hide();
		});

		// 加载省份数据
		function loadProvinces() {
			const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=中国&subdistrict=1&extensions=base`;
			$.get(url, function(response) {
				if (response.status === "1" && response.districts.length > 0) {
					const provinces = response.districts[0].districts;
					$("#province").empty().append('<option value="">请选择省份</option>');
					provinces.forEach(province => {
						$("#province").append(`<option value="${province.name}" data-adcode="${province.adcode}">${province.name}</option>`);
					});
				}
			});
		}

		// 当省份选择变化时，加载城市数据
		$("#province").change(function() {
			const provinceName = $(this).val();
			const provinceCode = $(this).find(":selected").data("adcode");
			$("#provincecode").val(provinceCode); // 更新省份代码

			if (provinceName) {
				const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=${provinceName}&subdistrict=1&extensions=base`;
				$.get(url, function(response) {
					if (response.status === "1" && response.districts.length > 0) {
						const cities = response.districts[0].districts;
						$("#city").empty().append('<option value="">请选择城市</option>');
						cities.forEach(city => {
							$("#city").append(`<option value="${city.name}" data-adcode="${city.adcode}">${city.name}</option>`);
						});
					}
				});
			}
		});

		// 当城市选择变化时，加载区域数据
		$("#city").change(function() {
			const cityName = $(this).val();
			const cityCode = $(this).find(":selected").data("adcode");
			$("#citycode").val(cityCode); // 更新城市代码

			if (cityName) {
				const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=${cityName}&subdistrict=1&extensions=base`;
				$.get(url, function(response) {
					if (response.status === "1" && response.districts.length > 0) {
						const areas = response.districts[0].districts;
						$("#area").empty().append('<option value="">请选择区域</option>');
						areas.forEach(area => {
							$("#area").append(`<option value="${area.name}" data-adcode="${area.adcode}">${area.name}</option>`);
						});
					}
				});
			}
		});

		// 当区域选择变化时，更新区域代码
		$("#area").change(function() {
			const areaCode = $(this).find(":selected").data("adcode");
			$("#areacode").val(areaCode); // 更新区域代码
		});

		// 提交表单，添加地址
		$("#addAddressForm").submit(function(event) {
			event.preventDefault(); // 阻止表单默认提交行为

			// 获取表单数据
			var contactName = $("#contactName").val();
			var tel = $("#tel").val();
			var province = $("#province").val();
			var city = $("#city").val();
			var area = $("#area").val();
			var provincecode = $("#provincecode").val();
			var citycode = $("#citycode").val();
			var areacode = $("#areacode").val();
			var detailAddress = $("#detailAddress").val();

			// 确保 userid 存在
			if (!window.userid) {
				alert("用户信息获取失败，请刷新页面重试！");
				return;
			}

			// 发起 AJAX 请求添加地址
			$.ajax({
				url: "address/add", // 添加地址路径
				type: "POST",
				data: {
					userid: window.userid, // 使用全局变量 userid
					name: contactName,
					tel: tel,
					province: province,
					city: city,
					area: area,
					provincecode: provincecode,
					citycode: citycode,
					areacode: areacode,
					address: detailAddress
				},
				success: function(response) {
					if (response === 1) { // 假设返回 1 表示添加成功
						alert("地址添加成功！");
						$("#addAddressModal").hide(); // 关闭模态框
					} else {
						alert("地址添加失败，请重试！");
					}
				},
				error: function(xhr, status, error) {
					console.error("添加地址失败:", error);
					alert("添加地址失败，请重试！");
				}
			});
		});
	});
</script>

</body>
</html>